<?php

class Core_Auth implements Zend_Auth_Adapter_Interface {
	
	/**
	 * 
	 * @var string
	 */
	protected $_login = null;

	/**
	 * 
	 * @var string
	 */
	protected $_namespace = null;
	
	/**
	 *
	 * @var Users
	 */
	private $user = null;
	
	/**
	 *
	 * @var Core_Auth
	 */
	static private $_instance = null;
	
	public static function getInstance() {
		if (self::$_instance === null) {
			self::$_instance = new self();
			self::$_instance->init();
		}
		return self::$_instance;
	}

	public function setLogin($login) {
		$this->_login = $login;
		return $this;
	}

	public function authenticate() {
		$session = new Zend_Session_Namespace($this->_namespace);
		$session->auth = false;
		
		$authHistory = new AuthHistory();
		$authHistory->setAdLogin($this->_login);
		$authHistory->setExtIp(Core_Tools::getUserIpAddr());
		
		$this->user = UsersQuery::create()->findOneByAdLogin($this->_login);
		
		if (!$this->user instanceof Users) {
			$authHistory->save();
			return new Zend_Auth_Result(Zend_Auth_Result::FAILURE, $this->_login, array('Invalid login'));
		}

		$authHistory->setUsers($this->user);
		$authHistory->save();
		
		$session->auth = true;
		$session->userId = $this->user->getId();
		return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $this->_login);
	}
	
	public static function init() {
		self::$_instance->_namespace = Core_Core::getInstance()->getConfigs()->session->namespace;
		$session = new Zend_Session_Namespace(self::$_instance->_namespace);
		if ($session->auth === null || $session->userId === null) {
			$session->auth = false;
			$session->userId = null;
		} else {
			self::$_instance->user = UsersQuery::create()->findOneById($session->userId);
			if (!self::$_instance->user instanceof Users) {
				$session->auth = false;
				$session->userId = null;
			}
		}
	}
	
	public static function logout() {
		$session = new Zend_Session_Namespace($this->_namespace);
		$session->auth = false;
		$session->userId = null;
		Skoda_Core::getInstance()->setUser(null);
	}

	public function getUser() {
		return $this->user;
	}
	
	public function isAuth() {
		$session = new Zend_Session_Namespace($this->_namespace);
		return $session->auth;
	}

}